package com.game.model;

import com.game.interfaces.LifeCycle;
import com.game.util.ImageUtil;
import com.game.util.PropertiesUtil;

import java.awt.*;

/**
 * @Author: tjc
 * @description
 * @Date Created in 22:07 2021-12-01
 */
public class ScoreBoard extends Module implements LifeCycle {

    private Sign[] locals;
    private StringBuilder points = new StringBuilder();

    private boolean overflow = false;
    private static final int Bit = 8;
    private static final int MAX_INT = 99999999;

    public static void main(String[] args) {
        ScoreBoard board = new ScoreBoard();
        board.init();
        board.addPoints(100);
        System.out.println(board.print());
        board.addPoints(100);
        System.out.println(board.print());
        board.addPoints(-50);
        System.out.println(board.print());
        board.addPoints(999999999);
        System.out.println(board.print());

    }

    public String print() {
        return points.toString();
    }

    public int getVal() {
        return Integer.parseInt(points.toString());
    }

    public void addPoints(int integral) {
        int a = getVal();
        int b = a + integral;
        if (b > MAX_INT) {
            b = MAX_INT;
            overflow = true;
        }
        full(b);
    }

    private void full(int val) {
        String valStr = String.valueOf(val);
        int diff = Bit - valStr.length();
        StringBuffer buff = new StringBuffer();
        while (diff-- > 0) {
            buff.insert(0, '0');
        }
        buff.append(valStr);
        points.setLength(0);
        points.append(buff.toString());
    }

    @Override
    public void init() {
        setLocalX(500);
        setLocalY(300);
        locals = new Sign[Bit];
        int offset = 0;
        for (int i = 0; i < Bit; i++) {
            Sign n = new Sign();
            n.x = localX + offset;
            n.y = localY;
            locals[i] = n;
            offset += PropertiesUtil.loadInt("score.num.width");
        }
        full(0);
    }


    @Override
    public void draw(Graphics g) {
        for (int i = 0; i < points.length(); i++) {
            g.drawImage(ImageUtil.numberImages[Integer.parseInt(String.valueOf(points.charAt(i)))], locals[i].x, locals[i].y, PropertiesUtil.loadInt("score.num.width"), PropertiesUtil.loadInt("score.num.length"), null);
        }
    }

    @Override
    public boolean alive() {
        return true;
    }

    private class Sign {
        int x;
        int y;
    }
}
